package com.bc.commoncore.concurrent;

import java.util.Map;
import java.util.Map.Entry;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class LambdasDemo {
	private static final Logger logger = LoggerFactory.getLogger(LambdasDemo.class);
	// ----------------------------------- 模拟任务方法示例
	
	public Object test(Object b) {
		Integer[] is = (Integer[])b;
		for(Integer it : is) {
			System.out.println("-------------->>方法0-->,"+it);			
		}
		try {
			Thread.sleep((long) (Math.random() * 1000));
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		
		System.out.println("-------------->>方法0-->完成");
		//throw new RuntimeException("异常");
		return "123";
	}
	
	public Object test1(Object b) {
		System.out.println("-------------->>方法1");
		try {
			Thread.sleep((long) (Math.random() * 2000));
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		System.out.println("-------------->>方法1,完成");
		return "执行成功!";
	}
	
	public Object test2(Object b) {
		System.out.println("-------------->>方法2");
		try {
			Thread.sleep((long) (Math.random() * 1000));
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		throw new RuntimeException("异常");
		//System.out.println("-------------->>方法2,完成");
		//return null;
	}
	
	// ------------------------------------ 任务组装使用
	
	/**
	 * 自己要完成的任务添加
	 */	
	public static void addTask() {
		LambdasDemo lam = new LambdasDemo();
		
		// 步骤1: 参数设置：几个任务方法就设置几
		ConcurrentTask ct = new ConcurrentTask(3, 10);
		// 同步
		//ConcurrentTask ct = new ConcurrentTask();
		
		// 步骤2: 装载任务方法
		ct.addTask(lam::test, new Integer[]{1,2}, "test");
		ct.addTask(lam::test1, new Object(), "test1");
		ct.addTask(lam::test2, new Object(), "test2");
		
		System.out.println("-------------->>已完成方法装载...");

		// 步骤3: 开始执行任务
		ct.start();
		
		System.out.println("-------------->>业务执行完成...");
		
		System.out.println("---------------------------------------------");
		
		System.out.println("----------------返回汇总结果如下--->");
		
		// 步骤4: 返回汇总结果待后续使用处理
		Map<String, MsgResult> result = ct.getResults();
		for (Object obj : result.entrySet()) {  
		    Entry entry = (Entry)obj;  
		    String key = (String) entry.getKey();  
		    MsgResult value = (MsgResult) entry.getValue();  
		    System.out.println("-------->"+key + "=" + value.getData()+",运行时间->"+value.getExeTime());  
		}    
	}
	
	/**
	 * 测试入口
	 * @param args
	 */
	public static void main(String[] args) {
		addTask();
	}
}
